package anatex.web;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import anatex.domain.Document;
import anatex.domain.Users;
import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.ui.Model;

@RooWebScaffold(path = "documents", formBackingObject = Document.class)
@RequestMapping("/documents")
@Controller
public class DocumentController {
	
	@RequestMapping(method = RequestMethod.POST, params="_docUpdate")
    public String updateFile(@Valid Document document, BindingResult result, Model model, HttpServletRequest request) {
        if (result.hasErrors()) {
            model.addAttribute("document", document);
            return "documents/update";
        }
        document.merge();
        return "redirect:/documents/" + encodeUrlPathSegment(document.getId().toString(), request);
    }
	
	@RequestMapping(params = {"find=ByOwner", "page"}, method = RequestMethod.GET)
    public String findDocumentsByOwner(@RequestParam("owner") Users owner, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "size", required = false) Integer size, Model model) {
        // tmp Tester

		//end of tester
		if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            model.addAttribute("documents", Document.findDocumentsByOwnerLimited(owner, page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo).getResultList());
            float nrOfPages = (float) Document.countDocumentsByOwner(owner) / sizeNo;
            
            model.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
        	model.addAttribute("documents", Document.findDocumentsByOwner(owner).getResultList());
        }
        return "documents/listByOwner";
    }
}
